<template>
	<div class="prizeBox">
		<div class="ladderBox">
			<el-tabs 
				v-model="editableTabsValue" 
				type="card" 
				:closable="repeatRecord == 0" 
				@tab-remove="removeLadder"
				:before-leave="changeTab"
				style="width:98%"
				>
				<el-tab-pane v-for="(item,index) in editableTabs" :key="item.name" :label="item.title" :name="item.name" >
					<AddPrize  :id="'ladder'+(index+1)" :prizeID="prizeID" :awardSort="index+1" @sendItem="addItem" :ref="'prizeItem'+(index+1)" @showStationDialog="showStationDialog" :lotterData="lotterData"></AddPrize>
				</el-tab-pane>
			</el-tabs>
		</div>
		<div class="ladderBtns">
			<div class="detailBtn btn next" @click="goDone(-1,$event)">上一步</div>
			<div class="detailBtn btn save" @click="goDone(0,$event)">保存</div>
			<div class="detailBtn btn next" @click="goDone(1,$event)">下一步</div>
		</div>
		<PowerStation v-if="showStation" @closeStation="showStationDialog" :type="type" :ids="activityGroup"></PowerStation>
	</div>
</template>

<script>
	let position = {
		'1':'一',
		'2':'二',
		'3':'三',
		'4':'四',
		'5':'五',
		'6':'六',
		'7':'七',
		'8':'八',
		'9':'九',
		'10':'十',
		'11':'十一',
		'12':'十二',
	}
	import Step from '_components/Step'
	import AddPrize from './children/AddPrize'
	import {SAVE_LOTTERY,
			EDIT_LOTTERY,
			DEL_LOTTERY,
			FIND_LOTTERY_BY_CODE,
			FIND_COUPON_RED_BY_CODE
		} from '@/config/url'
	import Bus from '@/bus.js'
	import PowerStation from '_components/PowerStation'

	export default {
		components: {
			Step,
			AddPrize,
			PowerStation	
		},
		created(){		
			this.initData()
			let that = this
			Bus.$off('refreshList')
			Bus.$on('refreshList',(val)=>{
				// that.$store.commit('setFirstCouponData',null)
				// that.$store.commit('setSecCouponData',null)
				this.itemList = null
				that.getFirstLottery()
			})	
			Bus.$off('refreshCoupon')
			Bus.$on('refreshCoupon',val=>{
				if(that.repeatRecord == 0){
					that.getFirstCounpon(val)
				}else{
					that.getSecCounpon(val)
				}
			})
			sessionStorage.setItem('lotterySort',1)
		},
		mounted(){
			this.getFirstLottery()
		},
		updated() {
			let that = this
			if(this.isAdd){
				this.$nextTick(() => {
					if($('.addLadderBtn').length == 0){
						if(this.repeatRecord == 0){
							$(".ladderBox .el-tabs__nav div:last-child").after('<div class="addLadderBtn el-tabs__item is-top"><span class="addIcon">+</span>添加阶梯</div>')
						}
						this.isAdd = false
					}
				})
				this.isAdd = false
			}
			if(this.repeatRecord == 1){
				$('.addLadderBtn').hide()
			}else{
				$('.addLadderBtn').show()
			}
		},
		data() {
			return {
				editableTabsValue: 'ladder1',
				editableTabs: [],
				tabIndex: 1,
				isAdd:true,
				tabNameIndex:1,//保存已经设置的内容，
				activityCode:sessionStorage.getItem('activityCode'),
				repeatRecord:sessionStorage.getItem('repeatRecord'),
				prizeID:null,//阶梯ID
				itemList:[],//保存的数据
				isRemove:false,//正在删除
				isAdding:false,//正在添加阶梯
				showStation:false,//显示电站
				type:{//电站选择
					type:1
				},
				lotterData:null,//初录结果
				isIdentical:null,//0 一致，1 不一致
				hasPrize:false,//是否有奖项
			}
		},
		watch:{
			tabIndex(n,o){
				if(n > 1 && n > o){
					this.isAdd = true
				}else{
					this.isAdd = false
				}
			}
		},
		methods: {
			addLadderBtn(data){
				let that = this
				this.$nextTick(() => {
					that.isAdd = false
					if($('.addLadderBtn').length == 0){
						$('.ladderBox').off('click', '.addLadderBtn')
						$('.ladderBox').on('click', '.addLadderBtn',function(){
							let isAdd = that.addLadder()
							that.initData()
							if(isAdd == '1'){
								that.getCode(that.editableTabs.length)
								this.editableTabsValue = 'ladder'+ that.editableTabs.length
								// Bus.$emit('refreshList')
							}
						})	
					}

					for(let i=0;i<data.length;i++){
						that.$refs['prizeItem'+(i+1)][0].updataData(data[i])
					}
				})
			},
			initData(){
				this.$store.commit('setFirstLotteryData',null)
				this.$store.commit('setSecLotteryData',null)
				this.$store.commit('setFirstCouponData',null)
				this.$store.commit('setSecCouponData',null)
			},
			getFirstLottery(id){
				let that = this
				this.$fetch(FIND_LOTTERY_BY_CODE,
					{
						"activityCode":this.activityCode,
						'repeatRecord':'0'
					}
				)
				.then(res=>{
					if(res.status == 1){
						// this.firstContent = res.data
						if(res.data.length < 1){
							this.addLadder()
							this.getCode(1)
							this.addLadderBtn()
							this.$store.commit('setFirstLotteryData',null)
						}else{
							let data = res.data
							this.lotterData = res.data
							this.editableTabs = []
							sessionStorage.setItem('activityScenes',res.data[0].activityScenes)
							this.$store.commit('setFirstLotteryData',res.data)
							that.itemList = res.data
							this.$store.commit('setCurrentLottery',res.data[sessionStorage.getItem('lotterySort')-1].id)
							that.prizeID = id||res.data[0].id
							if(that.editableTabs.length == 0){
								for(let i=0;i<res.data.length;i++){
									that.editableTabs.push({
										title: '阶梯'+ (i+1),
										name: 'ladder'+ (i+1),
										content: 'New Tab content'
									});
									that.tabIndex ++
									if(res.data[i].isIdentical == '1' && this.repeatRecord == 1){
										$('#tab-ladder'+(i+1)).css('color','red')
									}
								}
								this.addLadderBtn(data)
							}
							if(this.isAdding){
								this.editableTabsValue = 'ladder' + that.editableTabs.length
							}

							this.getFirstCounpon(this.$store.getters.getFirstLotteryData[sessionStorage.getItem('lotterySort') - 1].id)
							// this.prizeID = res.data[0].id
						}
					}
				})
				.catch(err=>{
					console.log(err)
					this.$message({
						message: '获取失败',
						type: 'warning'
					});
				})
			},
			getSecLottery(){
				let that = this
				let id = null
				this.$fetch(FIND_LOTTERY_BY_CODE,
					{
						"activityCode":this.activityCode,
						'repeatRecord':'1'
					}
				)
				.then(res=>{
					if(res.status == 1){
						if(res.data.length > 0){
							this.lotterData = res.data
							this.$store.commit('setSecLotteryData',res.data)
							this.getSecCounpon(res.data[sessionStorage.getItem('lotterySort')-1].id)
							this.$store.commit('setCurrentLottery',res.data[sessionStorage.getItem('lotterySort')-1].id)
							// that.prizeID = id||res.data[sessionStorage.getItem('lotterySort')-1].id
						}else{
							for(let i=0;i<this.lotterData.length;i++){
								this.getCode(i+1)
							}
							this.$store.commit('setSecCouponData','')
						}
					}
				})
				.catch(err=>{
					console.log(err)
					this.$message({
						message: '获取失败',
						type: 'warning'
					});
				})
			},
			getFirstCounpon(id){
				let that = this
				this.$fetch(FIND_COUPON_RED_BY_CODE,
					{
						'activityCode':this.activityCode,
						'repeatRecord':'0',
						'lotteryId':id
					}
				)
				.then(res=>{
					if(res.status == 1){
						if(res.data.length > 0){
							this.$store.commit('setFirstCouponData',null)
							this.$store.commit('setFirstCouponData',res.data)
							this.hasPrize = true
							if(that.repeatRecord == 1){
								that.getSecLottery()
							}
						}else{
							this.hasPrize = false
						}
					}
				})
				.catch(err=>{
					console.log(err)
					this.$message({
						message: '获取失败',
						type: 'warning'
					});
				})
			},
			getSecCounpon(id){
				id = this.$store.getters.getSecLotteryData[sessionStorage.getItem('lotterySort')-1].id
				this.$fetch(FIND_COUPON_RED_BY_CODE,
					{
						'activityCode':this.activityCode,
						'repeatRecord':'1',
						'lotteryId':id
					}
				)
				.then(res=>{
					if(res.status == 1){
						if(res.data.length > 0){
							this.$store.commit('setSecCouponData',null)
							this.$store.commit('setSecCouponData',res.data)
						}else{
							this.$store.commit('setSecCouponData',[])
							Bus.$emit('addPrize')
						}
					}
				})
				.catch(err=>{
					console.log(err)
					this.$message({
						message: '获取失败',
						type: 'warning'
					});
				})
			},
			showStationDialog(data){
				if(data){
					if(data.type == 1){
						let ids = []
						for(let item of data.data){
							this.activityBuild.push(item.id)
						}
						this.ids = ids.toString()
					}else{
						let ids = []
						for(let item of data.data){
							ids.push(item.id)
						}
						this.activityGroup = ids.toString()
					}
				}
				this.showStation = !this.showStation
			},
			goDone(type,e){
				if(type == -1){
					this.$router.push('/settingIndex/newRules')
					Bus.$emit("changeStep");
				}else{
					let pos = this.editableTabsValue.slice(-1);
					let itemRef = 'prizeItem'+pos
					let hasPrize = this.$refs['prizeItem'+(sessionStorage.getItem('lotterySort'))][0].hasPrize()//获取是否有奖项
					if(!hasPrize){
						this.$message({
							message: '请先添加奖项',
							type: 'warning'
						});
						return;
					}
					for(let i=0;i<this.lotterData.length;i++){
						if(this.$refs['prizeItem'+(i+1)] && this.$refs['prizeItem'+(i+1)].length > 0){
							this.$refs['prizeItem'+(i+1)][0].saveItem(i)
						}
					}
					this.isIdentical = this.repeatRecord == '0'?0:this.isIdentical
	
					let that = this
					this.$post(EDIT_LOTTERY,
						{
						"activityLotterys":this.itemList,
						}
					)
					.then(res=>{
						if(res.status == 1){
							this.$message({
								message: res.data,
								type: 'success'
							});
							if(type == 1){
								Bus.$emit('changeStep')
								this.$router.push('/settingIndex/activityDone')
							}
						}else{
							this.$message({
								message: res.data,
								type: 'warning'
							});
						}
					})
					.catch(err=>{
						console.log(err)
						this.$message({
							message: '获取code失败',
							type: 'warning'
						});
					})
				}
			},
			changeTab(n,o){
				if(!this.hasPrize){
					this.$message({
						message: '请先添加奖项',
						type: 'warning'
					});
					return  false;
				}
				let pos = o.slice(-1);
				if(/undefined/.test(n)){
					let num = this.editableTabs.length
					n = 'ladder'+(num)
				}
				let newPos = n.slice(-1);
				let itemRef = 'prizeItem'+pos
				let tabNew = 'prizeItem'+newPos
				sessionStorage.setItem('lotterySort',newPos)
				this.$store.commit('setPreLotterySort',pos)
				this.$store.commit('setPreLottery',this.$store.getters.getCurrentLottery)
				
				// if(this.isAdding){
				// 	this.$refs[itemRef][0].saveItem(sessionStorage.getItem('lotterySort')-1)
				// }
				if(this.$refs[tabNew]){
					if(this.$store.getters.getSecLotteryData){
						if(this.$store.getters.getSecLotteryData){
							this.$store.commit('setCurrentLottery',this.$store.getters.getSecLotteryData[newPos-1].id)
							// this.getFirstLottery()
							this.getSecCounpon(this.$store.getters.getSecLotteryData[newPos-1].id)
						}
					}else{
						if(this.$store.getters.getFirstLotteryData){
							this.$store.commit('setCurrentLottery',this.$store.getters.getFirstLotteryData[newPos-1].id)
							// this.getFirstLottery()
							this.getFirstCounpon(this.$store.getters.getFirstLotteryData[newPos-1].id)
						}
					}
				}
				if(this.repeatRecord == 0){
					this.$store.commit('setFirstCouponData',null)
				}else{
					this.$store.commit('setSecCouponData',null)
				}
				this.isRemove = false
				this.isAdding= false
			},
			addItem(data){//添加数据
				if(data.id){
					this.itemList[data.awardSort-1] = data
				}
			},
			getCode(num){//获取阶梯对应的编号
				let that = this
				let param = {
					"activityCode":this.activityCode,
					'repeatRecord':this.repeatRecord,
					"awardSort":num
				}
				if(this.repeatRecord == 1){
					param.awardObtain = '0'
					param.awardClaim = '0'
					param.awardSurprise = '0'
				}
				if(this.repeatRecord == 1){
					param.isIdentical = 1
				}
				this.$post(SAVE_LOTTERY,param
				)
				.then(res=>{
					if(res.status == 1){
						that.prizeID = res.data
						that.getFirstLottery()
					}else{
						this.$message({
							message: res.data,
							type: 'warning'
						});
					}
				})
				.catch(err=>{
					console.log(err)
					this.$message({
						message: '获取code失败',
						type: 'warning'
					});
				})
			},
			addLadder() {
				if(this.$refs['prizeItem'+(sessionStorage.getItem('lotterySort'))]){
					this.hasPrize = this.$refs['prizeItem'+(sessionStorage.getItem('lotterySort'))][0].hasPrize()//获取是否有奖项
					if(!this.hasPrize){
						this.$message({
							message: '请先添加奖项',
							type: 'warning'
						});
						return;
					}
				}
				let tabNum = $('.content .el-tabs__item').length
				console.log('阶梯数量：'+tabNum)
				if(tabNum == 10){
					this.$message({
						showClose: true,
						message: '最多添加9个阶梯'
					});
				}else{
					this.editableTabs.push({
						title: '阶梯'+ tabNum,
						name: 'ladder'+ tabNum,
						content: 'New Tab content'
					});
					this.editableTabsValue = 'ladder' + tabNum;
					this.isAdding = true
					$(".addLadderBtn").remove();

					return '1'
				}
			},
			removeLadder(targetName) {
				this.$confirm("确认删除该阶梯?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				})
				.then(() => {
					let pos = targetName.slice(-1);
					let lotterData = this.$store.getters.getSecLotteryData || this.$store.getters.getFirstLotteryData
					let that = this
					this.$fetch(DEL_LOTTERY,
						{
							"id":this.lotterData[pos-1].id,
						}
					)
					.then(res=>{
						if(res.status == 1){
							// this.getFirstLottery()
							let tabs = that.editableTabs;
							let activeName = that.editableTabsValue;
							if (activeName === targetName) {
								tabs.forEach((tab, index) => {
								if (tab.name === targetName) {
									let nextTab = tabs[index + 1] || tabs[index - 1];
									if (nextTab) {
										activeName = nextTab.name;
									}
								}
								});
							}
							this.hasPrize = true
							let newPos = activeName.slice(-1);
							that.editableTabsValue = 'ladder'+(newPos);
							that.editableTabs = tabs.filter(tab => tab.name !== targetName);
							this.$message({
								type: "success",
								message: "删除成功!"
							});
						}
					})
					.catch(err=>{
						console.log(err)
						this.$message({
							message: '删除失败',
							type: 'warning'
						});
					})
				})
				.catch(() => {});
					},
				},
				beforeDestroy(){
					Bus.$off('refreshList')
					Bus.$off('refreshCoupon')
				}
	}
</script>

<style>
	.ladderBtns {
		position: fixed;
		bottom: 0.15rem;
		left: 40%;
	}
	
	.ladderBtns .btn {
		width: 0.8rem;
		height: 0.2rem;
		background: #3395FF;
		border-radius: 8px;
		color: #fff;
		margin-left: 0.2rem;
	}
	
	/* .ladderBtns .next {
		background: #A9D0FF;
	} */
	.ladderBox{
		display: flex;
	}
	.addLadderBtn{
		width:1rem;
		height:0.23rem;
		line-height: 0.23rem;
		text-align: center;
		font-size:0.1rem;
		cursor: pointer;
		border-bottom:1px solid #F0F1F2;
	}
	.addIcon{
		color:#3395FF;
		font-size: 0.15rem;
	}
	.ladderBox .el-tabs__nav-scroll {
		border-bottom: 1px solid #F0F1F2;
	}
	
	.ladderBox .el-tabs--card>.el-tabs__header .el-tabs__item.is-active.is-closable {
		background-color: #fff;
		border-top: none;
		border-bottom: 3px solid #3395FF;
	}
	
	.ladderBox .el-tabs--card>.el-tabs__header .el-tabs__item,
	.ladderBox .el-tabs--card>.el-tabs__header .el-tabs__item:first-child {
		border: none;
	}
	.ladderBox .el-tabs--card > .el-tabs__header .el-tabs__item{
		background: none;
	    width: 0.8rem;
    	text-align: center;
    	font-size:0.1rem;
	}
	.ladderBox .el-tabs__nav div:first-child span{
		display: none;
	}
	.ladderBox .el-tabs--card>.el-tabs__header .el-tabs__item.is-active{
		border-bottom: 3px solid #3395FF !important;
	}
</style>